/*
 ============================================================================
 Name        : sigc_mod.c
 Author      : xm
 Version     : 1.0
 Copyright   : Long An
 Description : add phase in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"

void getIndex(char *s){
    int len = strlen(s);
    int i = 0;
    while(i<len){
        if('1' == s[i]){
            printf("%d,", len - i);
        }
        i++;
    }
}

void put_error(char *err_msg){
    printf("Content-type:text/html;charset=UTF-8\n\n");
    printf("%s.\n", err_msg);
}

void putJSON(char **azResult, int nrow, int ncolumn){
    int i=0, j=0, n=0;
    printf("Content-type:text/json;charset=UTF-8\n\n");
    printf("{ \"rows\": \"%d\", \"data\": [", nrow);
    for(i=1; i<=nrow; i++) {
 
        printf("{");
        char *phaseIndex = {0};
        for(j=0; j<ncolumn; j++) {
            if(j==0){
                phaseIndex = azResult[ (i*ncolumn) + j ];
            }
            printf("\"%s\": \"", azResult[j]);
            printf("%s", azResult[ (i*ncolumn) + j ]);
            if(j == ncolumn-1)
                printf("\"");
            else
                printf("\",");
            n++;
            if( strcmp(azResult[j], "pass_phase") == 0 ){ // insert lane
                //printf("\"%s\":\"", azResult[j]);//phaseLanes
                /*
                printf("\"phaseLanes\":\"");//
                PARAM p;
                sprintf(p.value, "%s", azResult[ (i*ncolumn) + j ]);
                get_channels(p, NULL);
                printf("\",");
                */
                
                printf("\"phases\":\"");//
                char str[32] = {0};                
                int phase = atoi(azResult[ (i*ncolumn) + j ]);
                _itoa(phase, str, 2);
                getIndex(str); 
                 printf("\",");
            }
        }
        if(i == nrow)
            printf("}\n\n");
        else
            printf("},\n\n");
    }
    printf("]}");
}

int main(void) {
        sqlite3 *db = NULL;
        int  nrow=0,ncolumn=0;
        char **azResult = NULL;
        char *zErrMsg =0;
        char sql[1000];
        char *input;
        char *req_method;
        int  rc;

        if(isvalid_cookie()!=0){
            return 0;
        }

        rc = sqlite3_open(PATH_DATABASE,&db);

        if (rc) {
            printf("Content-type:text/json;charset=utf-8\n\n");
            fprintf(stderr,"Can't open database:%s\n", sqlite3_errmsg(db));
            sqlite3_close(db);
            return 0;

        } else {
            req_method = getenv("REQUEST_METHOD");

            FILE* fp = (FILE*) stdin;
            input = getcgidata(fp, req_method);

            //PARAM un = getParam(input, "username");
            //printf("Your find is %s = %s  \n", un.key, un.value );

            //printf("Your input is %s<br>  \n", input );
            PARAM method  = getParam(input, "method");

            PARAM module_dev_node  = getParam(input, "module_dev_node");
            PARAM module_index     = getParam(input, "module_index");

            char last_modified[]      = {"datetime(CURRENT_TIMESTAMP,'localtime')"};

            if( strcmp(method.value, "update") == 0 ){
                sprintf(sql, " UPDATE [TB_MODULE]  \
                    set [module_dev_node]           = '%s',\
                       [last_modified]        = %s \
                    WHERE [module_index]        = %s ;",
                     module_dev_node.value,
                     last_modified,
                     module_index.value);
                    int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
                    printf("Content-type:text/json;charset=utf-8\n\n");
                    printf("{\"res\":\"%d\",\"msg\":\"%s\"}", sr, sqlite3_errmsg(db));
            } else {
                sprintf(sql, "select * from [TB_MODULE] order by MODULE_INDEX ");
                 
                rc = sqlite3_get_table(db, sql, &azResult, &nrow, &ncolumn, &zErrMsg);
                if (rc != SQLITE_OK) {
                    fprintf(stderr,"SQL error:%s\n", zErrMsg);
                    sqlite3_close(db);
                    return 0;

                } if (*azResult != NULL) {
                    // choose data format
                    putJSON(azResult, nrow, ncolumn);
                }
            }

            sqlite3_close(db);//关闭数据库
            return 0;

        }
        fflush(stdout);

    return EXIT_SUCCESS;
}



